import React, { Component } from 'react';
import { connect } from 'dva';
import { produce, Draft } from 'immer';
import { Select, Button, Table, Pagination, Input, Icon } from 'antd';
import styles from './commList.css';
import { DEFAULT_PAGE_NUM, DEFAULT_PAGE_SIZE } from '@/const';
import { deviceListEx, deviceKinds } from '@/services/statistics';
import { Dispatch, AnyAction } from 'redux';
import { Statistics } from '@/models/connect';
import { isMenuVisible } from '@/utils/utils';
import router from 'umi/router';
const { Option } = Select;
interface DeviceDetailProps {
  drugMedicalList?: Statistics;
  environmentList?: Statistics;
  vitalSignsList?: Statistics;
  byenergyList?: Statistics;
  deviceType?: Statistics;
  loading: boolean;
  dispatch: Dispatch<AnyAction>;
  deviceVisible?: Statistics;
  childList: any[];
}
interface DetailState {
  filterQueryParams: any;
  params: any;
  kinds: any;
}
class deviceDetail extends Component<DeviceDetailProps, DetailState> {
  state: DetailState = {
    filterQueryParams: {
      deviceId: '', // 资产编号
      deviceName: '',
      deviceTypeParentNo: this.props.deviceVisible.deviceTypeParentNo,
      deviceTypeNo: this.props.deviceVisible.deviceSonTypeNo,
      deviceState: this.props.deviceVisible.deviceState,
      stateCode: '',
      pageNum: DEFAULT_PAGE_NUM,
      pageSize: 10,
    },
    params: {
      deviceTypeNo: null,
    },
  };
  handleInputDrugNameChange = (e: string) => {
    // 资产编号
    const reg = /^-?(0|[1-9][0-9]*)(\.[0-9]*)?$/;
    if (
      (!isNaN(e.target.value) && reg.test(e.target.value)) ||
      e.target.value === '' ||
      e.target.value === '-'
    ) {
      e.persist();
      this.setState(
        produce((draft: Draft<DetailState>): void => {
          draft.filterQueryParams.deviceId = e.target.value;
        }),
      );
      // e.persist();
      // this.setState(
      //   produce((draft: Draft<DetailState>): void => {
      //     draft.filterQueryParams.deviceId = e.target.value;
      //     draft.value = e.target.value;
      //   }),
      // );
    } else {
      this.setState(
        produce((draft: Draft<DetailState>): void => {
          draft.filterQueryParams.deviceId = '';
          draft.value = '';
        }),
      );
    }
  };
  handleInputDrugNama = (e: string) => {
    // 设备名称
    e.persist();
    this.setState(
      produce((draft: Draft<DetailState>): void => {
        draft.filterQueryParams.deviceName = e.target.value.replace(/\s+/g, '');
      }),
    );
  };
  handleChangeType = (e: number) => {
    // 资产种类
    this.setState(
      produce((draft: Draft<DetailState>): void => {
        draft.filterQueryParams.deviceTypeNo = e;
      }),
    );
  };
  handleChangeCategory = (e: number) => {
    // 资产类别
    this.setState(
      produce((draft: Draft<DetailState>): void => {
        draft.filterQueryParams.deviceTypeParentNo = e;
        draft.filterQueryParams.deviceTypeNo = '';
        draft.params.deviceTypeParentNo = e;
      }),
    );
    const { dispatch } = this.props;
    if (e) {
      dispatch({ type: 'device/matchChildsByParents', payload: { deviceTypeNo: e } });
    } else {
      dispatch({ type: 'device/clearChildren' });
    }
  };
  handleChangeEqStatus = (e: number) => {
    // 设备状态
    this.setState(
      produce((draft: Draft<DetailState>): void => {
        draft.filterQueryParams.deviceState = e;
      }),
    );
  };
  handleChangeEuStatus = (e: number) => {
    // 在线状态
    this.setState(
      produce((draft: Draft<DetailState>): void => {
        draft.filterQueryParams.stateCode = e;
      }),
    );
  };
  // 页码变化
  handlePageChange: (pageNum: number, pageSize: number | undefined) => void = pageNum => {
    this.setState(
      produce((draft: Draft<DetailState>): void => {
        draft.filterQueryParams.pageNum = pageNum;
      }),
      () => this.handleFilterQuery(),
    );
  };
  handleFilterQuery = () => {
    // 搜索
    console.log(this.state.filterQueryParams);
    const { dispatch } = this.props;
    dispatch({ type: 'statistics/deviceDetail', payload: this.state.filterQueryParams });
  };
  deviceKindsSelect = async () => {
    const [err, data] = await deviceKinds(this.state.params);
    if (!err) {
      this.setState(
        produce((draft: Draft<DetailState>): void => {
          draft.kinds = data;
        }),
      );
    }
  };
  download = () => {
    //导出
    const { dispatch } = this.props;
    dispatch({
      type: 'statistics/drugListEx',
      payload: {
        params: this.state.filterQueryParams,
        typeApi: deviceListEx,
        name: '设备明细.xlsx',
      },
    });
  };
  handleStatus = (
    visibleId: number,
    id: string,
    deviceState: string,
    deviceTypeParentNo: string,
    deviceSonTypeNo: string,
  ) => {
    //页面切换
    const { dispatch } = this.props;
    dispatch({
      type: 'statistics/deviceVisible',
      payload: {
        visible: visibleId,
        visibleStatus: id,
        deviceState: deviceState,
        deviceTypeParentNo: deviceTypeParentNo + '',
        deviceSonTypeNo: deviceSonTypeNo + '',
      },
    });
  };
  componentWillMount() {
    this.handleFilterQuery();
    // this.deviceKindsSelect();
    const { dispatch } = this.props;

    dispatch({ type: 'device/clearChildren' });
    dispatch({ type: 'statistics/longDeviceType' });
    if (this.props.deviceVisible.deviceTypeParentNo) {
      dispatch({
        type: 'device/matchChildsByParents',
        payload: { deviceTypeNo: this.props.deviceVisible.deviceTypeParentNo },
      });
    }
  }
  columns: any = [
    {
      title: '资产编号',
      dataIndex: 'deviceId',
      key: 'deviceId',
      render: (text: any, record: any) => {
        const { dispatch } = this.props;
        return (
          <a
            onClick={() =>
              router.push(`/device/detail/${record.deviceSonTypeNo}/${record.deviceId}`)
            }
          >
            {text}
          </a>
        );
      },
    },
    {
      title: '设备名称',
      dataIndex: 'deviceName',
      key: 'deviceName',
    },
    {
      title: '资产类别',
      dataIndex: 'typeName',
      key: 'typeName',
    },
    {
      title: '资产种类',
      dataIndex: 'typeSonName',
      key: 'typeSonName',
    },
    {
      title: '设备状态',
      dataIndex: 'deviceState',
      key: 'deviceState',
      render: text => (
        <span style={{ color: text === '1' ? 'rgb(69, 235, 167)' : 'red' }}>
          {text === '1' ? '正常' : '异常'}
        </span>
      ),
    },
    {
      title: '状态明细',
      dataIndex: 'stateCode',
      key: 'stateCode',
    },
    {
      title: '设备报警次数',
      dataIndex: 'deviceAlam',
      key: 'deviceAlam',
    },
  ];
  render() {
    const { deviceDetail = [], longDeviceType = [], childList = [] } = this.props;
    return (
      isMenuVisible('iot:statistical:selectByDc') && (
        <div style={{ width: '100%' }}>
          <div
            className={styles['inforAnasy-container-top']}
            style={{ paddingLeft: '0', overflow: 'hidden' }}
          >
            <div className={styles['inforAnasy-container-top-btn']}>
              {isMenuVisible('iot:statistical:exportInfo') && (
                <Button
                  type="link"
                  onClick={() => {
                    this.download();
                  }}
                >
                  <img src={require('@/assets/images/add.png')} alt="" />
                  导出EXCEL
                </Button>
              )}
              {this.props.returnData === 'false' && (
                <Button
                  type="link"
                  onClick={() => {
                    // this.handleStatus(1, 'deviceCount', '1', '500', '10')
                    const { dispatch } = this.props;
                    dispatch({ type: 'statistics/deviceVisible', payload: { visible: 0 } });
                    dispatch({ type: 'statistics/deviceDetailReturn', payload: 'false' });
                  }}
                >
                  <Icon type="rollback" />
                </Button>
              )}
              {/* <Button type="link">
              <img src={require('@/assets/images/change.png')} alt="" />
            </Button> */}
            </div>
            <div style={{ clear: 'both' }}>
              <div className={styles['inforAnasy-container-top-input dev-search']}>
                <div className={styles['dev-search-select']}>
                  <Input
                    value={this.state.filterQueryParams.deviceId}
                    onChange={this.handleInputDrugNameChange}
                    addonBefore="资产编号"
                    placeholder="请输入资产编号"
                    type="text"
                  />
                </div>
                <div className={styles['dev-search-select']}>
                  <Input
                    onChange={this.handleInputDrugNama}
                    placeholder="请输入设备名称"
                    value={this.state.filterQueryParams.deviceName}
                    addonBefore="设备名称"
                    type="text"
                  />
                </div>
                <div className={styles['dev-search-select']}>
                  <span className={styles['dev-search-select-title']}>资产类别</span>
                  <Select
                    placeholder="请选择资产类别"
                    value={this.state.filterQueryParams.deviceTypeParentNo}
                    allowClear={true}
                    style={{ width: 200 }}
                    onChange={this.handleChangeCategory}
                  >
                    {/* <Option value=''>请选择</Option> */}
                    {_.map(longDeviceType, (item: any, index: number) => (
                      <Option key={index} value={item.deviceTypeNo}>
                        {item.deviceTypeName}
                      </Option>
                    ))}
                  </Select>
                </div>
                <div className={styles['dev-search-select']}>
                  <span className={styles['dev-search-select-title']}>资产种类</span>
                  <Select
                    placeholder="请先选择资产类别"
                    value={this.state.filterQueryParams.deviceTypeNo}
                    allowClear={true}
                    style={{ width: 200 }}
                    onChange={this.handleChangeType}
                  >
                    {/* <Option value="">请选择</Option> */}
                    {_.map(childList, (item: any, index: number) => (
                      <Option key={index} value={item.deviceTypeNo}>
                        {item.deviceTypeName}
                      </Option>
                    ))}
                  </Select>
                </div>
                <div className={styles['dev-search-select']}>
                  <span className={styles['dev-search-select-title']}>设备状态</span>
                  <Select
                    placeholder="请选择设备状态"
                    value={this.state.filterQueryParams.deviceState}
                    allowClear={true}
                    style={{ width: 200 }}
                    onChange={this.handleChangeEqStatus}
                  >
                    {/* <Option value=''>请选择</Option> */}
                    <Option value="1">正常</Option>
                    <Option value="2">异常</Option>
                  </Select>
                </div>
                {isMenuVisible('iot:statistical:selectByDc') && (
                  <Button
                    type="link"
                    className={styles['search']}
                    onClick={() => {
                      this.setState(
                        produce((draft: Draft): void => {
                          draft.filterQueryParams.pageNum = 1;
                        }),
                        () => {
                          this.handleFilterQuery();
                        },
                      );
                    }}
                  >
                    搜索
                  </Button>
                )}

                <Button
                  type="link"
                  className={styles['search']}
                  onClick={() => {
                    this.setState(
                      produce((draft: Draft): void => {
                        draft.filterQueryParams.deviceId = ''; // 资产编号
                        draft.filterQueryParams.deviceName = '';
                        draft.filterQueryParams.deviceTypeParentNo = undefined;
                        draft.filterQueryParams.deviceTypeNo = undefined;
                        draft.filterQueryParams.deviceState = undefined;
                      }),
                    );
                  }}
                >
                  重置
                </Button>
              </div>
            </div>
          </div>
          <Table
            scroll={{ y: '500px' }}
            pagination={false}
            columns={this.columns}
            className="deviceDetatil"
            dataSource={deviceDetail.rows}
            rowKey="deviceId"
          />
          <div className="pagination-box">
            <Pagination
              onChange={this.handlePageChange}
              defaultCurrent={this.state.filterQueryParams.pageNum}
              current={this.state.filterQueryParams.pageNum}
              total={deviceDetail.total ? deviceDetail.total : 0}
            />
            <span className="pagination-title-box">
              第{this.state.filterQueryParams.pageNum}/
              {Math.ceil(
                (deviceDetail.total ? deviceDetail.total : 0) /
                  this.state.filterQueryParams.pageSize,
              )}
              页 共{deviceDetail.total ? deviceDetail.total : 0}条
            </span>
          </div>
        </div>
      )
    );
  }
}
export default connect(({ loading, statistics, device }: any) => {
  return {
    loading: loading.effects['statistics/deviceDetail'],
    // loading: loading.effects['statistics/deviceVisible'],
    deviceDetail: statistics.deviceDetail,
    deviceVisible: statistics.deviceVisible,
    longDeviceType: statistics.longDeviceType,
    childList: device.matchChildsByParents,
    returnData: statistics.returnData,
  };
})(deviceDetail);
